<template>
  <view>
    <uni-section title="頭像" subTitle=" " type="line" padding>
      <image @click="uploadAvatar" class="w-20 h-20 rounded-full bg-gray-200" :src="user.avatar || userUrl"
        mode="aspectFill" />
    </uni-section>
    <uni-section title="用戶名" subTitle=" " type="line" padding>
      <uni-easyinput v-model="user.name" placeholder="請輸入内容"></uni-easyinput>
    </uni-section>
    <uni-section title="背景" subTitle=" " type="line" padding>
      <image @click="uploadCover" class="w-full h-20 bg-gray-200" :src="user.cover || userBgUrl"
        mode="aspectFill" />
    </uni-section>
    <uni-section title="簡介" subTitle=" " type="line" padding>
      <uni-easyinput type="textarea" autoHeight v-model="user.brief" placeholder="請輸入内容"></uni-easyinput>
    </uni-section>
    <button @click="editUserInfo">保存</button>
  </view>
</template>

<script>
import {
  httpUserInfo,
  httpUserEditInfo
} from '@/utils/api.js'
import { baseURL } from '../../utils/base';
export default {
  data() {
    return {
      user: {
        name: '',
        avatar: '',
        brief: '',
        cover:''
      },
      userId: '',
      userUrl: '../../static/img/user.jpg',
      userBgUrl: '../../static/img/user-bg.jpg',
    }
  },
  onLoad() {
    const user = getApp().globalData.user
    this.userId = user.userId || user.id
    this.getUserInfo(this.userId)
  },
  methods: {
    // 上传头像
    uploadAvatar() {
      uni.chooseImage({
        success: (chooseImageRes) => {
          const tempFilePaths = chooseImageRes.tempFilePaths
          uni.uploadFile({
            url: baseURL+ '/file/upload', //仅为示例，非真实的接口地址
            filePath: tempFilePaths[0],
            name: 'file',
            success: async (uploadFileRes) => {
              const file = JSON.parse(uploadFileRes.data)
              this.user.avatar = file.data.url
            }
          })
        }
      })
    },
    // 上传封面
    uploadCover() {
      uni.chooseImage({
        success: (chooseImageRes) => {
          const tempFilePaths = chooseImageRes.tempFilePaths
          uni.uploadFile({
            url: baseURL + '/file/upload', //仅为示例，非真实的接口地址
            filePath: tempFilePaths[0],
            name: 'file',
            success: async (uploadFileRes) => {
              const file = JSON.parse(uploadFileRes.data)
              this.user.cover = file.data.url
            }
          })
        }
      })
    },
    // 获取用户信息
    async getUserInfo(userId) {
      const { code, data } = await httpUserInfo(userId)
      if (code === 200) {
        this.user = data
      }
    },
    // 编辑信息
    async editUserInfo() {
      const { code } = await httpUserEditInfo(this.userId, this.user)
      if (code === 200) {
        uni.showToast({
          title: '更新成功'
        })
        uni.$emit('refresh')
        uni.navigateBack()
      }
    }
  }
}
</script>

<style lang="scss" scoped></style>